package com.souyun.serverblogjjwt;

import io.jsonwebtoken.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Date;

@SpringBootApplication
public class ServerBlogJjwtApplication {

    public static void main(String[] args) {
        String token = tokenMake();
        verifyToken(token);
        SpringApplication.run(ServerBlogJjwtApplication.class, args);
    }

    public static String tokenMake() {
        long now = System.currentTimeMillis();
        // 30秒过期
        long exp = now+1000*300;

        JwtBuilder builder = Jwts.builder();
        builder.setId("888888");              //设置唯一编号
        builder.setSubject("周叫兽");         //设置主题  可以是JSON数据
        builder.setIssuedAt(new Date());      //设置签发日期

        // 过期时间
        builder.setExpiration( new Date( exp ) );

        // 增加角色设置
        builder.claim( "roles","admin" );

        // 设置签名 使用HS256算法，并设置SecretKey(字符串)
        builder.signWith(SignatureAlgorithm.HS256,"souyun");

        // 构建 并返回一个字符串
        System.out.println( builder.compact() );
        return builder.compact();
    }

    public static void verifyToken(String token) {

        try {
            Claims claims = Jwts.parser().setSigningKey("souyun").parseClaimsJws(token).getBody();
            System.out.println(claims);

            System.out.println("id=" + claims.getId());
            System.out.println("sub=" + claims.getSubject());
            System.out.println("time=" + claims.getIssuedAt());

            System.out.println("roles=" + claims.get("roles"));
        }
        catch (ExpiredJwtException e) {
            System.out.println("token expired");
        } catch (SignatureException e) {
            System.out.println("token signature error");
        } catch (Exception e) {
            System.out.println("token error");
        }
    }
}
